package main

import (
	"flag"
	"fmt"
	"log"
	"net"
	"net/http"
	_ "net/http/pprof"
	"time"
)

var addr = flag.String("addr", "127.0.0.1:6000", "")

func main() {
	flag.Parse()
	go http.ListenAndServe(":8081", nil)
	success := 0
	failed := 0
	for i := 0; i < 2; i++ {
		go func() {
			for {
				conn, err := net.Dial("tcp", *addr)
				if err != nil {
					log.Printf("%v", err)
					if conn != nil {
						conn.Close()
					}
					return
				}
				connected := true
				t := time.Tick(1 * time.Millisecond)
				timer := time.NewTimer(10 * time.Second)
				b := make([]byte, 3)
				for connected {
					select {
					case <-t:
						conn.Write([]byte("abc"))
						conn.SetReadDeadline(time.Now().Add(2 * time.Second))
						n, err := conn.Read(b)
						if err != nil {
							log.Printf("%v", err)
							conn.Close()
							connected = false
						}
						if n != 3 {
							failed++
						} else {
							success++
						}
					case <-timer.C:
						conn.Close()
						connected = false
					}
				}
			}
		}()
	}
	timer := time.NewTimer(120 * time.Second)
	<-timer.C
	fmt.Printf("success: %d, failed: %d", success, failed)
}
